package com.example.backend.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;

/**
 * WebSocket事件监听器
 * 监听连接和断开事件
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WebSocketEventListener {

    private final WebSocketService webSocketService;

    /**
     * 监听WebSocket连接事件
     */
    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        Principal user = headerAccessor.getUser();
        
        if (user != null) {
            String username = user.getName();
            log.info("WebSocket连接建立: username={}, sessionId={}", 
                    username, headerAccessor.getSessionId());
            
            // 通知用户上线
            webSocketService.notifyUserOnline(username);
        }
    }

    /**
     * 监听WebSocket断开事件
     */
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        Principal user = headerAccessor.getUser();
        
        if (user != null) {
            String username = user.getName();
            log.info("WebSocket连接断开: username={}, sessionId={}", 
                    username, headerAccessor.getSessionId());
            
            // 通知用户下线
            webSocketService.notifyUserOffline(username);
        }
    }
}
